/*
 * Copyright (C) 2011 The Code Bakers
 * Authors: Cleuton Sampaio e Francisco Rodrigues
 * e-mail: thecodebakers@gmail.com
 * Project: http://code.google.com/p/biomagohc/
 * Site: http://www.thecodebakers.org
 *
 * Licensed under the GNU GPL, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://gplv3.fsf.org/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * @author Cleuton Sampaio e Francisco Rogrigues - thecodebakers@gmail.com
 */
package br.com.thecodebakers.biomago.activities;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import br.com.thecodebakers.biomago.R;
import br.com.thecodebakers.biomago.business.BioBO;
import br.com.thecodebakers.biomago.model.Elemento;

public class main extends Activity  implements OnItemClickListener {
    private static final String TAG = "main";
    private ListView listView;
	private String[] lv_arr = {};
	private ArrayAdapter<String> adapter = null;
	private List<String> listaElementos;
	private main selfRef;

	/** Called when the activity is first created. */
	
	private BioBO bo;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Log.d(TAG, "Entrou no create da activity main.");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bo = BioBO.getInstance(this.getApplicationContext());
        listView = (ListView)findViewById(android.R.id.list);
        listView.setTextFilterEnabled(true);
        registerForContextMenu(listView);
        selfRef = this;
        AdView adView = (AdView)this.findViewById(R.id.adView);  
        adView.loadAd(new AdRequest()); 
    }

    @Override
	protected void onStart() {
    	super.onStart();
        listaElementos = montarLista();
        lv_arr = listaElementos.toArray(new String[0]);
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, lv_arr);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);

	}




	private List<String> montarLista() {
    	List<String> listaItens = new ArrayList<String>();
    	SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
    	sdf.applyPattern("dd/MM/yyyy");
        for(Elemento e : this.bo.getListaPessoas()) {
        	listaItens.add(e.getNome().toUpperCase() + "; " + sdf.format(e.getNascimento()));
        }
        
        return listaItens;
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// Houve um soft-touch na lista
		// Pegamos o elemento e mostramos o biorritmo dele.
		String elementoBruto = listaElementos.get(arg2);
		String [] dados = elementoBruto.split(";");
		Intent i = new Intent(this.getApplicationContext(), GrafBio.class);
		i.putExtra("nome", dados[0]);
		i.putExtra("data", dados[1]);
		this.startActivity(i);
	}
	
	public void incluirRegistro (View view) {
		Intent i = new Intent(this.getApplicationContext(), Edicao.class);
		this.startActivity(i);
	}

	@Override
	public void onBackPressed() {
		moveTaskToBack(true);

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		Resources res = getResources();
	 	menu.setHeaderTitle(res.getString(R.string.mnu_titulo_menu));
	 	MenuInflater inflater = getMenuInflater();
	 	inflater.inflate(R.menu.menu_contexto, menu);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu_lista, menu);
	    return true;
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        final Elemento elemento = (Elemento)bo.getListaPessoas().get(info.position);
        SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        sdf.applyPattern("dd/MM/yyyy");
        switch (item.getItemId()) {
        case R.id.mnuCntExibir:
    		Intent i = new Intent(this.getApplicationContext(), GrafBio.class);
    		i.putExtra("nome", elemento.getNome());
    		i.putExtra("data", sdf.format(elemento.getNascimento()));
    		this.startActivity(i);
        	return true;
        case R.id.mnuCntExcluir:
      		Resources res = getResources();
       		String txtSim = res.getString(R.string.txtSim);
       		String txtNao = res.getString(R.string.txtNao);
               new AlertDialog.Builder(this).setMessage(R.string.msg_confirmar_exclusao)
               .setPositiveButton(txtSim, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int which) {
                   	comandarExclusao(elemento);
                   } })
               .setNegativeButton(txtNao, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int which) {
                       return;
                   } })
               .show(); 
        	
        	return true;
        default: return super.onContextItemSelected(item);
        }
	}

	protected void comandarExclusao(Elemento elemento) {
		int retorno = bo.deletePessoa(elemento);
		if (retorno != R.string.msg_inclusao_ok) {
			retorno = R.string.msg_erro_ao_excluir;
		}
		else {
			retorno = R.string.msg_exclusao_ok;
		}
		Resources res = this.getResources();
        new AlertDialog.Builder(this).setMessage(res.getString(retorno))
        .setNeutralButton(res.getString(R.string.lblOK), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	Intent i = new Intent (selfRef.getApplicationContext(), selfRef.getClass());
            	selfRef.startActivity(i);
            	selfRef.finish();
            } }).show(); 
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mnuIncluirRegistro:
			this.incluirRegistro(null);
			return true;
		case R.id.mnuAjuda:
			Intent i = new Intent (this.getApplicationContext(), Ajuda.class);
			this.startActivity(i);
			return true;
		default: return super.onOptionsItemSelected(item); 
		}
	}
	
}